package com.mall.order.biz.handler;

import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		CreateOrderContext contexts =(CreateOrderContext)context;

		List<CartProductDto> cartProductDtoList = contexts.getCartProductDtoList();
		for (CartProductDto cartProductDto : cartProductDtoList) {
			Long productNum = cartProductDto.getProductNum();
			Stock stock = stockMapper.selectStock(cartProductDto.getProductId());
			Long subNum = stock.getStockCount()-productNum;
//			if (subNum<0 || stock.getLockCount()!=0){//测试单用户情况下,如果多用户情况下，删除stock。getlock！=0
//				return false;
//			}

			if (subNum<0){
				return false;
			}
		}

		for (CartProductDto cartProductDto : cartProductDtoList) {

			Long productNum = cartProductDto.getProductNum();
			Stock stock = stockMapper.selectStock(cartProductDto.getProductId());

			Integer lockCount = stock.getLockCount();
			Long newlock = productNum+lockCount.longValue();

			Long newNum = stock.getStockCount()-productNum;
			stockMapper.updateStockSetStockCAndnewNum(newNum,newlock,cartProductDto.getProductId());
		}
		return true;
	}
}